package com.icss.ah.orderList.service;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.icss.ah.base.bean.EasyuiDataGridJson;
import com.icss.ah.base.bean.MchInfoBean;
import com.icss.ah.base.util.DateUtils;
import com.icss.ah.base.util.ResourceLoader;
import com.icss.ah.express.bean.ExpressGoodsBean;
import com.icss.ah.express.bean.ExpressUserBean;
import com.icss.ah.logistic.service.LogisticService;
import com.icss.ah.orderList.bean.MonthDict;
import com.icss.ah.orderList.bean.OrderBean;
import com.icss.ah.orderList.bean.OrderHeadBean;
import com.icss.ah.orderList.bean.OrderSheetBean;
import com.icss.ah.orderList.bean.ProductBean;
import com.icss.ah.util.HttpUtil;
import com.icss.j2ee.util.UUID;

@Service
@Transactional
public class OrderListService {
	private final Logger errlog = Logger.getLogger("E");
	private final Logger infolog = Logger.getLogger("I");
	
	@Autowired
	private SqlSessionTemplate sqlSessionTemplate;
	@Autowired
	private LogisticService logisticService;
	
	/**
	 * 查询订阅卡列表
	 * @param map
	 * @return
	 */
	public List queryCardList(HashMap map) {
		List list = new ArrayList();
		try{
			list = sqlSessionTemplate.selectList("OrderListBean.queryCardList", map);
			infolog.info("OrderListService|queryCardList|list:"+list);
			list = list == null ? new ArrayList() : list;
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("OrderListService|queryCardList", e);
		}
		return list;
	}
	public Long queryCardCount(HashMap map) {
		Long reValue = 0l;
		try {
			reValue = (Long)sqlSessionTemplate.selectOne("OrderListBean.queryCardCount", map);
			infolog.info("OrderListService|queryCardCount|reValue:"+reValue);
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("OrderListService|queryCardCount", e);
		} 
		return reValue;
	}
	/**
	 * 获取支付信息
	 * @param map
	 * @return
	 */
	public Map getPayInfo(HashMap map){
		Map m = new HashMap();
		try {
			m = sqlSessionTemplate.selectOne("OrderListBean.getPayInfo", map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return m;
	}
	
	//获取商户开通的微信、支付宝支付信息
	public MchInfoBean queryMchInfo(HashMap map){
		MchInfoBean mchInfo = null;
		try {
			mchInfo = sqlSessionTemplate.selectOne("OrderListBean.queryMchInfo", map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mchInfo;
	}
	/**
	 * 获取订单信息
	 * @param map
	 * @return
	 */
	public OrderBean getOrderByOrderNo(HashMap map){
		OrderBean orderInfo = null;
		try {
			orderInfo = sqlSessionTemplate.selectOne("OrderListBean.getOrderByOrderNo", map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return orderInfo;
	}
	
	public List<OrderBean> getOrderDetailList(String modelKey,HashMap map) {
		List<OrderBean> list = new ArrayList<OrderBean>();
		try {
			list = sqlSessionTemplate.selectList(modelKey,map);
			Map<String, String> dictMap = getAllMonthDictList();
			for (int i = 0; i < list.size(); i++) {
				OrderBean o = list.get(i);
				for (int j = 0; j < o.getProducts().size(); j++) {
					ProductBean p = o.getProducts().get(j);

					if (StringUtils.isNotEmpty(p.getITEM_TYPE())) {
						p.setITEM_TYPE_NAME(dictMap.get(p.getITEM_TYPE()));
					}
					if (StringUtils.isNotEmpty(p.getITEM_CODES())) {
						String itemCodesName = "";
						String[] arr = p.getITEM_CODES().split(",");
						for (String s : arr) {
							itemCodesName += dictMap.get(s) + ",";
						}
						p.setITEM_CODES_NAME(itemCodesName.substring(0, itemCodesName.length() - 1));
					}
				}
			}
			list = list == null ? new ArrayList<OrderBean>() : list;
		} catch (Exception ex) {
			ex.printStackTrace();
			list = new ArrayList<OrderBean>();
		} 
		return list;
	}
	
	public Map<String, String> getCurYearMonthDictMap() {
		HashMap query = new HashMap();
		query.put("yearCode", DateUtils.getCurrentDate("yyyy") + "%");
		List<MonthDict> dictList = getMonthDictList(query);
		Map<String, String> dictMap = new HashMap<String, String>();
		for (MonthDict dict : dictList) {
			dictMap.put(dict.getBaseCode(), dict.getCodeName());
		}
		// 4月订 3季度 2半年 1全年
		dictMap.put("4", "月订");
		dictMap.put("3", "季度");
		dictMap.put("2", "半年");
		dictMap.put("1", "全年");
		return dictMap;
	}
	
	public Map<String, String> getAllMonthDictList() {
		HashMap query = new HashMap();
		List<MonthDict> dictList = getAllMonthDictList(query);
		Map<String, String> dictMap = new HashMap<String, String>();
		for (MonthDict dict : dictList) {
			dictMap.put(dict.getBaseCode(), dict.getCodeName());
		}
		// 4月订 3季度 2半年 1全年
		dictMap.put("4", "月订");
		dictMap.put("3", "季度");
		dictMap.put("2", "半年");
		dictMap.put("1", "全年");
		return dictMap;
	}
	
	/*
	 * 获取商品月度选择的选项
	 */
	public List<MonthDict> getMonthDictList(HashMap query){
		List<MonthDict> resultList = sqlSessionTemplate.selectList("DictMapper.getMonthDictList", query);
		resultList = resultList == null ? new ArrayList<MonthDict>() : resultList;
		return resultList;
	}
	
	public List<MonthDict> getAllMonthDictList(HashMap query){
		List<MonthDict> resultList = sqlSessionTemplate.selectList("DictMapper.getAllMonthDictList", query);
		resultList = resultList == null ? new ArrayList<MonthDict>() : resultList;
		return resultList;
	}

	/**
	 * 获取订单信息
	 * @param hm
	 * @return
	 */
	public List<OrderBean> queryOrderExportList(HashMap hm) {
		List<OrderBean> list = new ArrayList<OrderBean>();
		try {
			list = sqlSessionTemplate.selectList("OrderListBean.queryOrderExportList",hm);
			list = list == null ? new ArrayList<OrderBean>() : list;
		} catch (Exception ex) {
			ex.printStackTrace();
			list = new ArrayList<OrderBean>();
		} 
		return list;
	}
	
	public List getOrderList(String modelKey,HashMap map) {
		List list = new ArrayList();
		try {
			list = sqlSessionTemplate.selectList(modelKey,map);
			list = list == null ? new ArrayList() : list;
		} catch (Exception ex) {
			ex.printStackTrace();
			list = new ArrayList();
		} 
		return list;
	}
	
	public Integer getOrderCount(String modelKey,HashMap map) {
		Integer reValue = 0;
		try {
			reValue = (Integer)sqlSessionTemplate.selectOne(modelKey,map);
		} catch (Exception ex) {
			ex.printStackTrace();
		} 
		return reValue;
	}
	
	public List getProductList(String modelKey,HashMap map) {
		List list = new ArrayList();
		try {
			list = sqlSessionTemplate.selectList(modelKey,map);
			list = list == null ? new ArrayList() : list;
		} catch (Exception ex) {
			ex.printStackTrace();
			list = new ArrayList();
		} 
		return list;
	}
	
	public Long getProductCount(String modelKey,HashMap map) {
		Long reValue = 0l;
		try {
			reValue = (Long)sqlSessionTemplate.selectOne(modelKey,map);
		} catch (Exception ex) {
			ex.printStackTrace();
		} 
		return reValue;
	}
	/**
	 * 接单
	 * @param hm
	 * @return
	 */
	public boolean agreeOrder(HashMap hm){
		boolean result = false;
		try{
			hm.put("LAST_TIMESTAMP", System.currentTimeMillis());
			int f = sqlSessionTemplate.update("OrderListBean.updateOrderStatus", hm);
			if(f>0){
				hm.put("OPE_UUID", new UUID().toString());
				sqlSessionTemplate.insert("OrderListBean.insertOrderOpeLog", hm);
			}
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	/**
	 * 拒单
	 * @param hm
	 * @return
	 */
	public boolean RefusedOrder(HashMap hm){
		boolean result = false;
		try{
			hm.put("LAST_TIMESTAMP", System.currentTimeMillis());
			int f = sqlSessionTemplate.update("OrderListBean.updateOrderStatus", hm);
			if(f>0){
				hm.put("OPE_UUID", new UUID().toString());
				sqlSessionTemplate.insert("OrderListBean.insertOrderOpeLog", hm);
			}
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	/**
	 * 批量处理订单
	 * @param hm
	 * @return
	 */
	public boolean operateBatch(HashMap hm){
		boolean result = false;
		try{
			String LOGISTICS_INTO = "";
			String LOGISTICS_STATUS = "";
			String orderStatus = hm.get("orderStatus").toString();
			if("2".equals(orderStatus)){
				//订单处理
				hm.put("LAST_TIMESTAMP", System.currentTimeMillis());
				hm.put("ORDER_STATUS", "3");
				
				LOGISTICS_INTO = "订单已处理";
				LOGISTICS_STATUS = "010002001";
				
				hm.put("OPE_UUID", new UUID().toString());
				hm.put("OPE_DESC", "店家已处理");
				
			} else if("3".equals(orderStatus)) {
				//订单发货
				hm.put("LAST_TIMESTAMP", System.currentTimeMillis());
				hm.put("ORDER_STATUS", "4");
					
				LOGISTICS_INTO = "订单已发货";
				LOGISTICS_STATUS = "010002002";
					
				hm.put("OPE_UUID", new UUID().toString());
				hm.put("OPE_DESC", "店家已发货");
			}
			//更改订单状态
			int f = sqlSessionTemplate.update("OrderListBean.updateOrderStatusBatch", hm);
			if(f>0){
				try{
					//写入操作日志
					sqlSessionTemplate.insert("OrderListBean.insertOrderOpeLogBatch", hm);
				} catch (Exception e) {
					errlog.error("orderListService|operateBatch|异常：",e);
				}
				//写入物流信息  订单已发货
				HashMap<String,Object> map = new HashMap<String,Object>();
				map.put("UUID", java.util.UUID.randomUUID().toString());
				map.put("corpId", hm.get("corpId"));
				map.put("orderUuids", hm.get("orderUuids"));
				map.put("LOGISTICS_INTO", LOGISTICS_INTO);
				map.put("LOGISTICS_STATUS", LOGISTICS_STATUS);
				logisticService.addLogisticInfo("LogisticBean.addLogisticInfoBatch", map);
			}
			if("3".equals(orderStatus)){
				hm.put("UUID", java.util.UUID.randomUUID().toString());
				sqlSessionTemplate.insert("OrderListBean.insertDeliverByUidBatch", hm);//发货--添加订单配送信息
			}
			//发送模版消息
			List tempList = sqlSessionTemplate.selectList("LogisticBean.getLogisitInfoBatch", hm);//获取物流信息
			if(tempList!=null && !tempList.isEmpty()){
				for(Iterator<HashMap> i = tempList.iterator();i.hasNext();){
					HashMap data = i.next();
					
					try{
						logisticService.sendTemplate(hm,data);//发送模版消息
						
						String deliverType = hm.get("deliverType") == null ? "" : hm.get("deliverType").toString();
						if("3".equals(deliverType)){
							hm.put("orderUuid", data.get("ORDER_UUID").toString());
							logisticService.sendTemplateDispatcher(hm);//送货员发送模版消息
						}
						OrderHeadBean orderHeadBean = new OrderHeadBean();
						orderHeadBean.setCorpId(hm.get("corpId").toString());
						orderHeadBean.setOrderNo(data.get("ORDER_NO").toString());
						orderHeadBean.setOrderUuid(data.get("ORDER_UUID").toString());
						orderHeadBean.setShopId(hm.get("shopId").toString());
						orderHeadBean.setUserCode(data.get("USER_CODE").toString());
						logisticService.autoConfirmOrder(orderHeadBean);
					} catch (Exception e) {
						errlog.error("orderListService|operateBatch|autoConfirmOrder|异常：",e);
					}
					
				}
			}
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("orderListService|operateBatch|异常：",e);
		}
		return result;
	}
	/**
	 * 发货
	 * @param hm
	 * @return
	 */
	public boolean shipOrder(HashMap hm,HashMap map){
		boolean result = false;
		try{
			hm.put("LAST_TIMESTAMP", System.currentTimeMillis());
			int f = sqlSessionTemplate.update("OrderListBean.updateOrderStatus", hm);
			f = sqlSessionTemplate.update("OrderListBean.updateOrderMailOrderNo", hm);
			if(f>0){
				hm.put("OPE_UUID", new UUID().toString());
				sqlSessionTemplate.insert("OrderListBean.insertOrderOpeLog", hm);
			}
			
			hm.put("uuid", new UUID().toString()); 
			Integer count = sqlSessionTemplate.selectOne("OrderListBean.queryDeliverByUid", map);
			if(count==0){
				sqlSessionTemplate.insert("OrderListBean.insertDeliverByUid", hm);//发货--添加订单配送信息
			}
			sqlSessionTemplate.insert("LogisticBean.addLogisticInfo", map);//写入物流信息  订单已发货
			HashMap data = sqlSessionTemplate.selectOne("LogisticBean.getLogisitInfo", map);//获取物流信息
			
			try{
				logisticService.sendTemplate(map,data);//用户发送模版消息
//				String deliverType = hm.get("deliverType").toString();
//				infolog.info("orderListService|shipOrder|deliverType:"+deliverType);
//				if("3".equals(deliverType)){
//					hm.putAll(map);
//					logisticService.sendTemplateDispatcher(hm);//送货员发送模版消息
//				}
			
				OrderHeadBean orderHeadBean = new OrderHeadBean();
				orderHeadBean.setCorpId(hm.get("corpId").toString());
				orderHeadBean.setOrderNo(hm.get("orderNo").toString());
				orderHeadBean.setOrderUuid(hm.get("orderUuid").toString());
				orderHeadBean.setShopId(hm.get("shopId").toString());
				orderHeadBean.setUserCode(data.get("USER_CODE").toString());
				logisticService.autoConfirmOrder(orderHeadBean);
			} catch (Exception e) {
				errlog.error("orderListService|shipOrder|autoConfirmOrder|异常：",e);
			}
			
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("orderListService|shipOrder|异常：",e);
		}
		return result;
	}
	
	/**
	 * 评价回复
	 * @param hm
	 * @return
	 */
	public boolean evalOrder(HashMap hm){
		boolean result = false;
		try{
			hm.put("LAST_TIMESTAMP", System.currentTimeMillis());
			int f = sqlSessionTemplate.update("OrderListBean.updateOrderStatus", hm);
			if(f>0){
				hm.put("OPE_UUID", new UUID().toString());
				sqlSessionTemplate.insert("OrderListBean.insertOrderOpeLog", hm);
			}
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	/**
	 * 退款操作
	 * @param payMap
	 * @return
	 */
	public String agreeRefund(HashMap hm,HashMap payMap){
		String result = "0, 请稍后再试";
		try{
			//获取支付人编码
			String USER_CODE = payMap.get("USER_CODE") == null ? "" : payMap.get("USER_CODE").toString();
			//获取退货单号
			String out_refund_no = payMap.get("REFUND_NO") == null ? "" : payMap.get("REFUND_NO").toString();
			//获取退货金额
			String refund_fee = payMap.get("REFUND_MONEY") == null ? "0" : payMap.get("REFUND_MONEY").toString();
			//获取原支付单号
			String oldPayId = payMap.get("PAY_ID") == null ? "" : payMap.get("PAY_ID").toString();
			//获取原支付流水
			String oldTransactionId = payMap.get("TRANSACTION_ID") == null ? "" : payMap.get("TRANSACTION_ID").toString();
			
			Integer payStatus = sqlSessionTemplate.selectOne("OrderListBean.queryPayStatusRefund",payMap);
			payStatus = payStatus == null ? -1 : payStatus;
			if(payStatus==1){
				result = "2, 订单已退款";
			} else {
				
				String httpUrl = ResourceLoader.getInstance("icss").getString("payServiceUrl") + "/quickPay/quickOrderRefund.do";
				String icssMchCode = ResourceLoader.getInstance("icss").getString("icssMchCode");
				HashMap query = new HashMap();
				query.put("mchCode", icssMchCode);
				query.put("userCode", USER_CODE);
				query.put("sellNo", out_refund_no);
				query.put("oldSellNo", oldPayId);
				query.put("oldtransactionId", oldTransactionId);
				
				//处理订单金额，微信订单以分为单位
				DecimalFormat format = new DecimalFormat("0.00");
				refund_fee = format.format(Double.parseDouble(refund_fee));
				
				query.put("orderMoney", refund_fee);
				
				JSONObject dataJson = JSONObject.fromObject(query);
				JSONObject resultJson = HttpUtil.connectHttp(httpUrl, dataJson.toString(), "utf-8");
				System.out.println("OrderListAction==========resultJson:"+resultJson.toString());
				boolean opeFlag= resultJson.getBoolean("success");
				if(opeFlag){
					JSONObject reObj = resultJson.getJSONObject("obj");
					String resultCode = reObj.getString("RESULT_CODE");
					if("000".equals(resultCode)){
						HashMap map = (HashMap)JSONObject.toBean(reObj, HashMap.class);
//						String PAY_ID = reObj.getString("PAY_ID");
						String PAY_STATUS = reObj.getString("PAY_STATUS");
//						String RETURN_CODE = reObj.getString("RETURN_CODE");
//						String RETURN_CONTENT = reObj.getString("RETURN_CONTENT");
						sqlSessionTemplate.update("OrderListBean.updatePayStatusNew", map);
						if("1".equals(PAY_STATUS)){
//							String TRANSACTION_ID = reObj.getString("TRANSACTION_ID");
							hm.put("LAST_TIMESTAMP", DateUtils.getCurrentDate("yyyy-MM-dd HH:mm:ss"));
							hm.put("applyStatus", "1");
							hm.put("reason", "退款成功");
							sqlSessionTemplate.update("OrderListBean.updateRefundStatus", hm);
							result = "1, 订单退款成功";
						} else {
							result = "2, 订单退款失败";
						}
					} else {
						result = "2, 退款服务异常，请稍后再试";
					}
				} else{
					result = "2, 退款异常，请稍后再试";
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			result = "2,"+e.getMessage();
		}
		return result;
	}
	/**
	 * 退款操作
	 * @param payMap
	 * @return
	 */
	/*public String agreeRefund(HashMap hm,HashMap payMap){
		String result = "0, 请稍后再试";
		try{
			//获取退货单号
			String out_refund_no = payMap.get("REFUND_NO") == null ? "" : payMap.get("REFUND_NO").toString();
			//获取退货金额
			String refund_fee = payMap.get("REFUND_MONEY") == null ? "0" : payMap.get("REFUND_MONEY").toString();
			//获取商户信息
			MchInfoBean mchInfo = queryMchInfo(payMap);
			//封装退货单信息
			payMap.put("WX_MCH_ID", mchInfo.getWxMchId());
			payMap.put("ALI_MCH_ID", mchInfo.getAliMchId());
			payMap.put("SELL_TYPE", "1");
			payMap.put("orderMoney", refund_fee);
			
			Integer payStatus = sqlSessionTemplate.selectOne("OrderListBean.queryPayStatusRefund",payMap);
			payStatus = payStatus == null ? -1 : payStatus;
			if(payStatus==1){
			   result = "2, 订单已退款";
			} else if(payStatus==0){
				HashMap oldPayMap = getOldPayInfo(payMap);
				//封装退款所需参数map
				HashMap oldRefundMap = mapChangeToRefundMap(oldPayMap);
				//查询退款信息
				String httpUrl = ResourceLoader.getInstance("icss").getString("payServiceUrl") + "/weixinPayService/payRefundQuery";
				JSONObject dataJson = JSONObject.fromObject(oldRefundMap);
				System.out.println("OrderListAction==========dataJson:"+dataJson.toString());
				JSONObject resultJson = HttpUtil.connectHttp(httpUrl, dataJson.toString(), "utf-8");
				System.out.println("OrderListAction==========resultJson:"+resultJson.toString());
				String ERRORCODE = resultJson.getString("ERRORCODE");
				if(!"0".equals(ERRORCODE)){
					//生成退货单
					HashMap newPayMap = createNewPayInfo(payMap);
					//封装退款所需参数map
					HashMap refundMap = mapChangeToRefundMap(newPayMap);
					
					//调用退款接口，申请退款
					httpUrl = ResourceLoader.getInstance("icss").getString("payServiceUrl") + "/weixinPayService/payApplyRefund";
					dataJson = JSONObject.fromObject(refundMap);
					System.out.println("OrderListAction==========dataJson:"+dataJson.toString());
					resultJson = HttpUtil.connectHttp(httpUrl, dataJson.toString(), "utf-8");
					System.out.println("OrderListAction==========resultJson:"+resultJson.toString());
					ERRORCODE = resultJson.getString("ERRORCODE");
					HashMap map = (HashMap)JSONObject.toBean(resultJson, HashMap.class);
					if("0".equals(ERRORCODE)){
						map.put("pStatus", "1");
					} else {
						map.put("pStatus", "2");
						result = "2, 订单退款失败";
					}
					sqlSessionTemplate.update("OrderListBean.updatePayStatus", map);
					if("0".equals(ERRORCODE)){
						hm.put("LAST_TIMESTAMP", DateUtils.getCurrentDate("yyyy-MM-dd HH:mm:ss"));
						hm.put("applyStatus", "1");
						hm.put("reason", "退款成功");
						sqlSessionTemplate.update("OrderListBean.updateRefundStatus", hm);
						result = "1, 订单退款成功";
					}
				}else {
					result = "2, 订单已退款";
				}
				
			}else {
				//生成退货单
				HashMap newPayMap = createNewPayInfo(payMap);
				//封装退款所需参数map
				HashMap refundMap = mapChangeToRefundMap(newPayMap);
				
				
				
				//调用退款接口，申请退款
				String httpUrl = ResourceLoader.getInstance("icss").getString("payServiceUrl") + "/weixinPayService/payApplyRefund";
				JSONObject dataJson = JSONObject.fromObject(refundMap);
				System.out.println("OrderListAction==========dataJson:"+dataJson.toString());
				JSONObject resultJson = HttpUtil.connectHttp(httpUrl, dataJson.toString(), "utf-8");
				System.out.println("OrderListAction==========resultJson:"+resultJson.toString());
				String ERRORCODE = resultJson.getString("ERRORCODE");
				HashMap map = (HashMap)JSONObject.toBean(resultJson, HashMap.class);
				if("0".equals(ERRORCODE)){
					map.put("pStatus", "1");
				} else {
					map.put("pStatus", "2");
					result = "1, 订单退款失败";
				}
				sqlSessionTemplate.update("OrderListBean.updatePayStatus", map);
				if("0".equals(ERRORCODE)){
					hm.put("LAST_TIMESTAMP", DateUtils.getCurrentDate("yyyy-MM-dd HH:mm:ss"));
					hm.put("applyStatus", "1");
					hm.put("reason", "退款成功");
					sqlSessionTemplate.update("OrderListBean.updateRefundStatus", hm);
					result = "1, 订单退款成功";
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			result = "2,"+e.getMessage();
		}
		return result;
	}*/

	public HashMap getOldPayInfo(HashMap map) {
		HashMap oldPayMap = new HashMap();
		try{
			String orderNo = (String)map.get("orderNo");
			String SELL_TYPE = (String)map.get("SELL_TYPE");
			if("1".equals(SELL_TYPE)){
				String PAY_ID = (String)map.get("PAY_ID");
				map.put("F_PAY_ID", PAY_ID);
				orderNo =  (String)map.get("REFUND_NO");
			} else {
				map.put("F_PAY_ID", "");
			}
			map.put("SELL_NO", orderNo);
			//获取最后订单流水
			String oldPayId = sqlSessionTemplate.selectOne("OrderListBean.getLastPayId", map);
			map.put("PAY_ID", oldPayId);
			map.put("PAY_STATUS", "0");
			String time = DateUtils.getCurrentDate("yyyy-MM-dd HH:mm:ss");
			map.put("PAY_DAY", time.substring(0, 10));
			map.put("PAY_TIME", time.substring(11, 19));
			map.put("curTime", time);
			//返回支付流水信息
			oldPayMap.putAll(map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return oldPayMap;
	}
	
	/**
	 * 生成新的支付/退货单
	 * @param map
	 * @return
	 */
	public HashMap createNewPayInfo(Map map){
		HashMap newPayMap = new HashMap();
		try{
			String orderNo = (String)map.get("orderNo");
			String SELL_TYPE = (String)map.get("SELL_TYPE");
			if("1".equals(SELL_TYPE)){
				String PAY_ID = (String)map.get("PAY_ID");
				map.put("F_PAY_ID", PAY_ID);
				orderNo =  (String)map.get("REFUND_NO");
			} else {
				map.put("F_PAY_ID", "");
			}
			map.put("SELL_NO", orderNo);
			//获取订单流水数
			Integer count = sqlSessionTemplate.selectOne("OrderListBean.getPayOrderCount", map);
			//生成新的支付流水
			String newPayId = "000"+count;
			newPayId = orderNo+newPayId.substring(newPayId.length()-3, newPayId.length());
			map.put("PAY_ID", newPayId);
			map.put("PAY_STATUS", "0");
			String time = DateUtils.getCurrentDate("yyyy-MM-dd HH:mm:ss");
			map.put("PAY_DAY", time.substring(0, 10));
			map.put("PAY_TIME", time.substring(11, 19));
			map.put("curTime", time);
			//保存支付流水信息
			int f = sqlSessionTemplate.insert("OrderListBean.insertPayInfo", map);
			if(f>0){
				//返回支付流水信息
				newPayMap.putAll(map);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return newPayMap;
	}
	/**
	 * 封装退款所需参数map
	 * @param map
	 * @return
	 */
	public HashMap mapChangeToRefundMap(HashMap payMap){
		String payType = payMap.get("PAY_TYPE") == null ? "" : payMap.get("PAY_TYPE").toString();
		//获取退货金额
		String refund_fee = payMap.get("REFUND_MONEY") == null ? "0" : payMap.get("REFUND_MONEY").toString();
		String mchCode = payMap.get("MCH_CODE") == null ? "" : payMap.get("MCH_CODE").toString();
		String out_trade_no = payMap.get("F_PAY_ID") == null ? "" : payMap.get("F_PAY_ID").toString();
		String trade_no = payMap.get("TRANSACTION_ID") == null ? "" : payMap.get("TRANSACTION_ID").toString();
		String total_fee = payMap.get("PAY_MONEY") == null  ?  "0" : payMap.get("PAY_MONEY").toString();
		String op_user_id = payMap.get("userCode") == null ? "" : payMap.get("userCode").toString();
		String PAY_ID = payMap.get("PAY_ID") == null ? "" : payMap.get("PAY_ID").toString();
		
		//处理订单金额，微信订单以分为单位
		DecimalFormat format = new DecimalFormat("0");
		refund_fee = format.format(Double.parseDouble(refund_fee)*100);
		total_fee = format.format(Double.parseDouble(total_fee)*100);
		
		HashMap refundMap = new HashMap();
		refundMap.put("payType", payType);
		refundMap.put("mchCode", mchCode);
		refundMap.put("out_trade_no", out_trade_no);
		refundMap.put("trade_no", trade_no);
		refundMap.put("out_refund_no", PAY_ID);
		refundMap.put("total_fee", total_fee);
		refundMap.put("refund_fee", refund_fee);
		refundMap.put("op_user_id", op_user_id);
		
		return refundMap;
	}
	/**
	 * 更新订单状态
	 * @param hm
	 * @return
	 */
	public boolean updateOrderStatus(HashMap hm){
		boolean result = false;
		try{
			hm.put("LAST_TIMESTAMP", System.currentTimeMillis());
			int f = sqlSessionTemplate.update("OrderListBean.updateOrderStatus", hm);
			if(f>0){
				hm.put("OPE_UUID", new UUID().toString());
				sqlSessionTemplate.insert("OrderListBean.insertOrderOpeLog", hm);
			}
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 更新退款状态
	 * @param hm
	 * @return
	 */
	public boolean updateRefundStatus(HashMap hm){
		boolean result = false;
		try{
			hm.put("LAST_TIMESTAMP", System.currentTimeMillis());
			int f = sqlSessionTemplate.update("OrderListBean.updateRefundStatus", hm);
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 查询支付方式、订单支付信息、退款信息
	 * @param hm
	 * @return
	 */
	public HashMap queryPayMap(HashMap hm) {
		HashMap map = new HashMap();
		try {
			map = sqlSessionTemplate.selectOne("OrderListBean.queryPayMap", hm);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map == null ? new HashMap() : map;
	}

	/**
	 * 修改订单折扣
	 * @param hm
	 * @return
	 */
	public boolean updateDiscount(HashMap hm) {
		boolean result = false;
		try{
			sqlSessionTemplate.update("OrderListBean.updateDiscount", hm);
			result = true;
		}catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	/**
	 * 订单改价
	 * @param hm
	 * @return
	 */
	public String updatePrice(HashMap hm){
		String result = "0, ";
		try {
			//获取订单信息
			HashMap map = sqlSessionTemplate.selectOne("OrderListBean.queryOrderMap", hm);
			
			hm.put("orderUuid", map.get("ORDER_UUID").toString());
			hm.put("userCode", map.get("USER_CODE").toString());
			hm.put("yhType", 4);
			hm.put("yhName", "优惠");
			//获取订单优惠情况
			Map yhMap = sqlSessionTemplate.selectOne("OrderListBean.queryYhMap", hm);
			yhMap = yhMap == null ? new HashMap() : yhMap;
			if(yhMap.containsKey("YH_UUID")){
				//修改订单优惠
				hm.put("yhUuid", yhMap.get("YH_UUID").toString());
				sqlSessionTemplate.update("OrderListBean.updateDiscount", hm);
			}else {
				//新增订单优惠
				if (Double.parseDouble(hm.get("discountMoney").toString())!=0) {
					hm.put("yhUuid",  java.util.UUID.randomUUID().toString());
					sqlSessionTemplate.insert("OrderListBean.insertDiscount", hm);
				}
			}
			//修改订单最终费用
			sqlSessionTemplate.update("OrderListBean.updateDeliverMoney", hm);
			result = "1,success";
		} catch (Exception e) {
			result = "0,"+e.getMessage();
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 获得订单优惠列表
	 * @param map
	 * @return
	 */
	public List<Map> getDiscountList(HashMap map) {
		List list = new ArrayList();
		try {
			list = sqlSessionTemplate.selectList("OrderListBean.getDiscountList", map);
			list = list == null ? new ArrayList() : list;
		} catch (Exception ex) {
			ex.printStackTrace();
			list = new ArrayList();
		} 
		return list;
	}

	/**
	 * 获得订单优惠列表数量
	 * @param modelKey
	 * @param map
	 * @return
	 */
	public Long getDiscountCount(HashMap map) {
		Long reValue = 0l;
		try {
			reValue = (Long)sqlSessionTemplate.selectOne("OrderListBean.getDiscountCount", map);
		} catch (Exception ex) {
			ex.printStackTrace();
		} 
		return reValue;
	}

	/**
	 * 获得物流时间列表
	 * @param modelKey
	 * @param map
	 * @return
	 */
	public List<Map> queryDeliverList(HashMap map) {
		List list = new ArrayList();
		try {
			list = sqlSessionTemplate.selectList("OrderListBean.queryDeliverList", map);
			list = list == null ? new ArrayList() : list;
		} catch (Exception ex) {
			ex.printStackTrace();
			list = new ArrayList();
		} 
		return list;
	}
	/**
	 * 获得物流车辆列表
	 * @param modelKey
	 * @param map
	 * @return
	 */
	public List<Map> getWlCarList(HashMap map) {
		List list = new ArrayList();
		try {
			list = sqlSessionTemplate.selectList("OrderListBean.getWlCarList", map);
			list = list == null ? new ArrayList() : list;
		} catch (Exception ex) {
			ex.printStackTrace();
			list = new ArrayList();
		} 
		return list;
	}
	/**
	 * 获得物流人员列表
	 * @param modelKey
	 * @param map
	 * @return
	 */
	public List<Map> getWlUserList(HashMap map) {
		List list = new ArrayList();
		try {
			list = sqlSessionTemplate.selectList("OrderListBean.getWlUserList", map);
			list = list == null ? new ArrayList() : list;
		} catch (Exception ex) {
			ex.printStackTrace();
			list = new ArrayList();
		} 
		return list;
	}
	
	/**
	 * 获取快递公司信息列表
	 */
	public List<Map<String, Object>> queryExpressList(Map<String, String> map){
		List list = new ArrayList();
		try {
			list = sqlSessionTemplate.selectList("OrderListBean.queryExpressList", map);
			list = list == null ? new ArrayList() : list;
		} catch (Exception e) {
			e.printStackTrace();
			list = new ArrayList();
			errlog.error("orderListService|queryExpressList|异常：",e);
		} 
		return list;
	}
	/**
	 * 获取寄件人信息
	 */
	public ExpressUserBean querySenderInfo(Map<String, String> map){
		ExpressUserBean bean = new ExpressUserBean();
		try {
			bean = sqlSessionTemplate.selectOne("OrderListBean.querySenderInfo", map);
		} catch (Exception e) {
			e.printStackTrace();
			bean = new ExpressUserBean();
			errlog.error("orderListService|querySenderInfo|异常：",e);
		} 
		return bean;
	}
	/**
	 * 获取收件人信息
	 */
	public ExpressUserBean queryReceiverInfo(Map<String, String> map){
		ExpressUserBean bean = new ExpressUserBean();
		try {
			bean = sqlSessionTemplate.selectOne("OrderListBean.queryReceiverInfo", map);
		} catch (Exception e) {
			e.printStackTrace();
			bean = new ExpressUserBean();
			errlog.error("orderListService|queryReceiverInfo|异常：",e);
		} 
		return bean;
	}
	/**
	 * 快递商品列表
	 */
	public List<ExpressGoodsBean> queryGoodsList(Map<String, String> map){
		List<ExpressGoodsBean> list = new ArrayList<ExpressGoodsBean>();
		try {
			list = sqlSessionTemplate.selectList("OrderListBean.queryGoodsList", map);
			list = list == null ? new ArrayList<ExpressGoodsBean>() : list;
		} catch (Exception e) {
			e.printStackTrace();
			list = new ArrayList<ExpressGoodsBean>();
			errlog.error("orderListService|queryGoodsList|异常：",e);
		} 
		return list;
	}
	
	/**
	 * 电子面单保存
	 */
	public void insertSheetInfo(Map<String, String> map){
		try {
			sqlSessionTemplate.insert("OrderListBean.insertSheetInfo", map);
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("orderListService|insertSheetInfo|异常：",e);
		}
	}
	
	/**
	 * 电子面单查询
	 */
	public OrderSheetBean queryOrderSheet(Map<String, String> map){
		OrderSheetBean bean = new OrderSheetBean();
		try {
			bean = sqlSessionTemplate.selectOne("OrderListBean.queryOrderSheet", map);
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("orderListService|queryOrderSheet|异常：",e);
		}
		return bean == null ? new OrderSheetBean() : bean;
	}
	
	/**
	 * page print
	 * @param map
	 * @return
	 */
	public EasyuiDataGridJson queryOrderPrintList(Map<String, String> map){
		EasyuiDataGridJson dataGridJson = new EasyuiDataGridJson();
		try {
			List<OrderBean> list = sqlSessionTemplate.selectList("OrderListBean.queryOrderPrintList",map);
//			Long total = sqlSessionTemplate.selectOne("OrderListBean.queryOrderPrintListCount",map);
			dataGridJson.setRows(list);
//			dataGridJson.setTotal(total);
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("orderListService|queryOrderPrintList|异常：",e);
		}
		return dataGridJson;
	}
	
	/**
	 * 发票邮寄
	 * @param map
	 * @return
	 */
	public boolean saveExpressBill(HashMap<String,Object> map) {
		boolean result=false;
		try {
			sqlSessionTemplate.update("OrderListBean.updateBillStatus", map);
			result = true;
		} catch (Exception ex) {
			ex.printStackTrace();
			result = false;
		} 
		return result;
	}

}
